<template>
  <div class="app-container nursing-item-page">
    <!-- 搜索表单 -->
    <div class="search-container" v-show="showSearch">
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="护理项目名称" prop="name">
              <el-input
                v-model="queryParams.name"
                placeholder="请输入护理项目名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select 
                v-model="queryParams.status" 
                placeholder="请选择状态" 
                clearable
                style="width: 130px;"
                :popper-append-to-body="false"
                popper-class="status-select-dropdown"
              >
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=" " class="search-buttons">
              <el-button type="default" icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 操作按钮行 -->
    <el-row :gutter="10" class="toolbar-row">
      <el-col :span="12">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['service:item:add']"
          class="action-btn"
        >新增护理项目</el-button>
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['service:item:edit']"
          class="action-btn"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['service:item:remove']"
          class="action-btn"
        >删除</el-button>
      </el-col>
      <el-col :span="12" class="text-right">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="itemList" 
      @selection-change="handleSelectionChange"
      class="nursing-item-table"
      stripe
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="护理图片" align="center" prop="image" width="100">
        <template #default="scope">
          <image-preview :src="imageUrl+scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="护理项目名称" align="center" prop="name" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="价格（元）" align="center" prop="price" width="120">
        <template #default="scope">
          <span class="price-text">{{ Number(scope.row.price).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" prop="unit" width="100" />
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="创建人" align="center" prop="user_name" width="120" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope"><span>{{ parseTime(scope.row.createTime) }}</span></template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" effect="plain">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="240" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['service:item:edit']">编辑</el-button>
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button link :type="scope.row.status === 1 ? 'warning' : 'success'" @click="handleToggleStatus(scope.row)">
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['service:item:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      class="nursing-item-pagination"
    />

    <!-- 添加或修改护理项目对话框 -->
    <el-dialog :title="title" v-model="open" width="650px" append-to-body class="nursing-item-dialog">
      <el-form ref="itemRef" :model="form" :rules="rules" label-width="120px" class="nursing-item-form">
        <el-form-item label="护理项目名称" prop="name" class="form-item-inline">
          <el-input 
            v-model="form.name" 
            placeholder="请输入护理项目名称" 
            maxlength="10" 
            show-word-limit 
            class="full-width-input"
          />
        </el-form-item>
        <el-form-item label="价格" prop="price" class="form-item-inline">
          <el-input-number 
            v-model="form.price" 
            :min="0" 
            :precision="2" 
            :step="10" 
            controls-position="right" 
            class="full-width-number"
          />
          <span style="margin-left: 8px; color: #606266;">元</span>
        </el-form-item>
        <el-form-item label="单位" prop="unit" class="form-item-inline">
          <el-input 
            v-model="form.unit" 
            placeholder="请输入单位（如：次、小时）" 
            maxlength="5" 
            show-word-limit 
            class="full-width-input"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort" class="form-item-inline">
          <el-input-number 
            v-model="form.sort" 
            :min="1" 
            :max="9999" 
            controls-position="right" 
            class="full-width-number"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status" class="form-item-inline">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="护理图片" prop="image">
          <div>
            <image-upload v-model="form.image" />
            <div style="color:#999;margin-top:8px;font-size:12px;">请上传大小不超过 <span style="color:#00CC99;font-weight:500;">5MB</span> 格式为 <span style="color:#00CC99;font-weight:500;">png/jpg/jpeg</span> 的文件</div>
          </div>
        </el-form-item>
        <el-form-item label="护理项目描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="3"
            :maxlength="50" 
            show-word-limit 
            placeholder="请输入护理项目的详细描述" 
            class="full-width-textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看护理项目 -->
    <el-dialog title="查看护理项目" v-model="openView" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="护理图片">
          <image-preview :src="imageUrl + (viewRow.image || '')" :width="60" :height="60" />
        </el-descriptions-item>
        <el-descriptions-item label="护理项目名称">{{ viewRow.name }}</el-descriptions-item>
        <el-descriptions-item label="价格（元）">{{ Number(viewRow.price || 0).toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ viewRow.unit }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ viewRow.sort }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ viewRow.creatorName || viewRow.creator }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewRow.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewRow.status === 1 ? 'success' : 'danger'">
            {{ viewRow.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item :span="2" label="项目描述">{{ viewRow.description }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Item">
import { listItem, getItem, delItem, addItem, updateItem } from "@/api/system/item.js"

const { proxy } = getCurrentInstance()
const imageUrl = ""
const itemList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    status: null
  },
  rules: {
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

/** 查询护理项目列表 */
function getList() {
  loading.value = true
  listItem(queryParams.value).then(response => {
    console.log('后端返回的完整数据:', response)
    console.log('response.rows:', response.rows)
    
    if (response.rows && response.rows.length > 0) {
      console.log('第一条数据:', response.rows[0])
      console.log('第一条数据的id:', response.rows[0].id)
    }
    
    itemList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    image: null,
    price: null,
    unit: null,
    sort: null,
    creator: null,
    createTime: null,
    status: null,
    description: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("itemRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加护理项目"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  
  console.log('编辑按钮点击，获取ID:', _id)
  console.log('row数据:', row)
  
  if (!_id) {
    proxy.$modal.msgError("数据异常，无法获取项目ID")
    return
  }
  
  getItem(_id).then(response => {
    console.log('getItem返回的数据:', response)
    console.log('response.data:', response.data)
    
    if (response.data) {
      form.value = response.data
      open.value = true
      title.value = "修改护理项目"
    } else {
      proxy.$modal.msgError("获取项目详情失败")
    }
  }).catch(error => {
    console.error('获取项目详情失败:', error)
    proxy.$modal.msgError("获取项目详情失败")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["itemRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addItem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除护理项目编号为"' + _ids + '"的数据项？').then(function() {
    return delItem(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 启用/禁用 */
function handleToggleStatus(row) {
  console.log('点击启用/禁用按钮，row数据:', row)
  console.log('row.id:', row.id)
  
  if (!row.id) {
    proxy.$modal.msgError("数据异常，无法获取项目ID")
    return
  }
  
  const nextStatus = row.status === 1 ? 0 : 1
  const text = nextStatus === 1 ? "启用" : "禁用"
  const payload = { id: row.id, status: nextStatus }
  
  console.log('发送的payload:', payload)
  
  proxy.$modal.confirm('确认要' + text + '该项目吗?').then(function () {
    return updateItem(payload)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
    getList()
  }).catch(() => {})
}

// 查看
const openView = ref(false)
const viewRow = ref({})
function handleView(row) {
  // 若需要拿最新详情，解开下行并确保后端接口可用
  // getItem(row.id).then(res => { viewRow.value = res.data; openView.value = true })
  viewRow.value = { ...row }
  openView.value = true
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('service/item/export', {
    ...queryParams.value
  }, `item_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped lang="scss">
/* 页面整体样式 */
.nursing-item-page {
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  /* 搜索容器 */
  .search-container {
    background: #fff;
    padding: 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);

    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #333;
      }

      .search-buttons {
        display: flex;
        justify-content: flex-end;
        
        :deep(.el-form-item__content) {
          justify-content: flex-end;
        }

        .el-button {
          min-width: 80px;
        }
      }
    }
  }

  /* 工具栏 */
  .toolbar-row {
    background: #fff;
    padding: 16px 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    align-items: center;

    .action-btn {
      margin-right: 12px;
      font-weight: 500;
    }

    .text-right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }
  }

  /* 表格样式 */
  .nursing-item-table {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    :deep(.el-table__header) {
      th {
        background: #f5f7fa;
        color: #333;
        font-weight: 600;
        font-size: 14px;
        padding: 16px 0;
      }
    }

    :deep(.el-table__body) {
      td {
        padding: 14px 0;
        font-size: 14px;
        color: #606266;
      }

      .el-table__row:hover {
        background-color: #f5f7fa;
      }
    }

    /* 价格文字样式 */
    .price-text {
      color: #00CC99;
      font-weight: 600;
      font-size: 15px;
    }

    /* 操作按钮样式 */
    :deep(.el-button--text) {
      padding: 4px 8px;
      margin: 0 4px;
    }
  }
}

/* 护理项目对话框样式 */
.nursing-item-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(135deg, #00CC99 0%, #00b386 100%);
    padding: 20px;
    margin: 0;

    .el-dialog__title {
      color: #fff;
      font-size: 18px;
      font-weight: 600;
    }

    .el-dialog__headerbtn {
      top: 20px;
      right: 20px;

      .el-dialog__close {
        color: #fff;
        font-size: 20px;

        &:hover {
          color: #f0f0f0;
        }
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 30px;
  }

  .nursing-item-form {
    .form-item-inline {
      display: flex;
      align-items: flex-start;
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        flex-shrink: 0;
        font-weight: 500;
        color: #333;
        font-size: 14px;
        line-height: 40px;
        padding-right: 12px;
      }

      :deep(.el-form-item__content) {
        flex: 1;
        display: flex;
        align-items: flex-start;
      }

      /* 全宽输入框 */
      .full-width-input {
        width: 100%;
      }

      /* 全宽数字输入框 */
      .full-width-number {
        width: 100%;
      }

      /* 全宽文本域 */
      .full-width-textarea {
        width: 100%;
      }
    }

    /* 图片上传表单项 */
    :deep(.el-form-item) {
      margin-bottom: 20px;
    }
  }

  /* 对话框底部按钮 */
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 10px 0 0;

    .el-button {
      min-width: 90px;
      padding: 10px 20px;
      font-weight: 500;
    }
  }
}

/* 输入框获取焦点时的样式 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  border-color: #00CC99;
  box-shadow: 0 0 0 2px rgba(0, 204, 153, 0.1);
}

/* 分页样式 */
:deep(.el-pagination) {
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
  justify-content: center;
}

/* 通用样式 */
.text-right {
  text-align: right;
}

.mb8 {
  margin-bottom: 8px;
}
</style>

<style lang="scss">
/* 状态下拉框样式 - 全局样式 */
.status-select-dropdown {
  min-width: 150px !important;
  
  .el-select-dropdown__item {
    padding: 12px 16px;
    font-size: 14px;
  }
}
</style>
